package com.ruoyi.assemble.datamanage.service.impl;


import com.ruoyi.assemble.common.utils.FileUtil;
import com.ruoyi.assemble.common.utils.SystemInfoUtils;
import com.ruoyi.assemble.common.utils.UUIDUtils;
import com.ruoyi.assemble.common.utils.Variable;
import com.ruoyi.assemble.datamanage.domain.*;
import com.ruoyi.assemble.datamanage.domain.dto.*;
import com.ruoyi.assemble.datamanage.mapper.DataLoadMapper;
import com.ruoyi.assemble.datamanage.mapper.DataMaintenanceMapper;
import com.ruoyi.assemble.datamanage.service.IDataLoadService;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.WritableResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: DataLoadService
 * @author:
 * @date: 2022/7/14 14:28
 * @param:
 * @return:
 **/
@Service
public class DataLoadServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(DataLoadServiceImpl.class);

    public static final String WINDOWS = "windows";

    public static final String DATE = "DATE";

    public static final String CODE = "code";

    public static final int TWO = 2;

    public static final int THREE = 3;

    private static final String NAMESPACE = "com.ruoyi.assemble.datamanage.mapper.DataLoadMapper";

    public List<FileMenu> selectAllType() {
        return sqlSession.selectList(NAMESPACE+".selectAllType",null);
    }

    private List<String> acceptUploadFileTypes = Arrays.asList(new String[]{"csv"});

    @Value("${upload.image-folder-path}")
    private String uploadImagePath;

    /*@Autowired
    private ExportService exportService;*/

    @Resource
    private SqlSession sqlSession;

    @Resource
    private DataLoadMapper dataLoadRepository;

    @Resource
    private DataMaintenanceMapper dataMaintenanceRepository;

    @Resource
    private ResourceLoader resourceLoader;

    public List<LoadRecord> getRecordList(DataLoadRecordQuery query) {
        return dataLoadRepository.selectList(query);
    }

    public List<Map> getMaintenanceList(Map argsMap) {
        argsMap.put("searchList", String.valueOf(argsMap.get("searchList")).split(","));
        return dataMaintenanceRepository.selectList(argsMap);
    }

    /**
     * @description: 获取设置弹窗信息
     * @author: FFP
     * @time: 2022/1/18 13:22
     */
    public FileSetResult getTableSetInfo(Map argsMap) {
        String code = String.valueOf(argsMap.get("code"));
        String id = String.valueOf(argsMap.get("id"));
        FileSetResult fileSetResult = new FileSetResult();
        List<FileSetInfo> tableData = new ArrayList<>();
        List<TableConfig> tableConfigs = selectTableHead(code);
        Map<String, Object> params = new HashMap();
        params.put("id", id);
        LoadRecord record = sqlSession.selectOne(NAMESPACE+".selectOneRecord",params);
        //原文件列名字
        List<String> fileName = Arrays.asList(record.getFileTitle().split("\\,"));
        //匹配成功字段Index
        List<String> fileIndex = Arrays.asList(record.getAfterOrder().split("\\,"));
        //匹配成功字段Code
        List<String> tableCode = Arrays.asList(record.getAfterCode().split("\\,"));
        //插入字段代码
        List<String> codeList = tableConfigs.stream().map(TableConfig::getCode).collect(Collectors.toList());
        //插入名称
        List<String> nameList = tableConfigs.stream().map(TableConfig::getName).collect(Collectors.toList());
        //必须填写字段
        List<String> isNotNullList = tableConfigs.stream().filter(item -> StringUtils.equals(item.getIsNull(), "NO")).map(TableConfig::getName).collect(Collectors.toList());
        //封装选项框数据
        List<SelectMap> selectCollect = tableConfigs.stream().map(itme -> {
            SelectMap selectMap = new SelectMap();
            selectMap.setKey(itme.getName());
            selectMap.setValue(itme.getCode());
            return selectMap;
        }).collect(Collectors.toList());
        //封装数据
        for (int i = 0; i <= fileName.size() - 1; i++) {
            FileSetInfo fileSetInfo = new FileSetInfo();
            fileSetInfo.setFileTitle(fileName.get(i));
            if (nameList.contains(fileName.get(i))) {
                int index = nameList.indexOf(fileName.get(i));
                fileSetInfo.setTableName(nameList.get(index));
                fileSetInfo.setTableCode(codeList.get(index));
                fileSetInfo.setOldCode(codeList.get(index));
            }
            tableData.add(fileSetInfo);
        }
        fileSetResult.setMustCode(StringUtils.join(isNotNullList, ","));
        fileSetResult.setMatchedList(tableCode);
        fileSetResult.setTableConfig(selectCollect);
        fileSetResult.setFileSetInfo(tableData);
        return fileSetResult;
    }

    public List<TableConfig> selectTableHead(String tableCode) {
        return sqlSession.selectList(NAMESPACE + ".selectTableHead", tableCode);
    }

    /**
     * 加载文件数据
     *
     * @param argsMap
     * @return
     */
    public Map<String, String> loadData(Map argsMap) {
        String id = String.valueOf(argsMap.get("id"));
        String projectId = String.valueOf(argsMap.get("projectId"));
        String stepId = String.valueOf(argsMap.get("stepId"));
        String nodeId = String.valueOf(argsMap.get("nodeId"));
        String typeCode = String.valueOf(argsMap.get("typeCode"));
        String userCode = String.valueOf(argsMap.get("userCode"));
        Map<String, String> backResult = new HashMap<>();
        /*获取全部表头*/
        List<TableConfig> tableHead = selectTableHead(typeCode);
        Map<String, String> map = new HashMap<>();
        map.put("projectId", projectId);
        map.put("tableName", typeCode);
        map.put("id", id);
        /*获取当前加载记录*/
        LoadRecord record = sqlSession.selectOne(NAMESPACE + ".selectOneRecord", map);
        /*获取文件路径*/
        String filePath = record.getFilePath();
        /*获取配置后的的字段code*/
        List<String> column = Arrays.asList(StringUtils.split(record.getAfterCode(), ","));
        List<String> columnCodes = new ArrayList(column);
        /*获取配置后的的文件表头对应列*/
        String[] columnOrders = StringUtils.split(record.getAfterOrder(), ",");
        /*配置后的的字段name*/
        List<String> columnNames = new ArrayList<>();
        /*配置后的的字段类型*/
        List<String> columnTypes = new ArrayList<>();
        /*所有数据*/
        List<Map<String, String>> allData = sqlSession.selectList(NAMESPACE + ".selectDataPaging", map);
        /*插入主键*/
        List<String> priKey = tableHead.stream().filter(n -> "PRI".equals(n.getPrimaryKey())).map(TableConfig::getCode).collect(Collectors.toList());
        /*插入字段是否允许为空*/
        List<String> isNullList = new ArrayList<>();
        StringJoiner updateJoiner = new StringJoiner(",");
        String errorText = "";
        try {
            for (String code : columnCodes) {
                Optional<TableConfig> option = tableHead.stream()
                    .filter(n -> n.getCode().equals(code))
                    .findFirst();
                TableConfig config = new TableConfig();
                if (option.isPresent()) {
                    config = option.get();
                    columnNames.add(config.getName());
                    columnTypes.add(config.getType());
                    isNullList.add(config.getIsNull());
                    /*检查更新操作对那些字段进行更新*/
                    updateJoiner.add(String.format("%s%s%s%s%s", code, "=", "values(", code, ")"));
                } else {
                    errorText = "请检查字段对应配置";
                    break;
                }
            }
            String fileRealPath = uploadImagePath + filePath;
            if(!SystemInfoUtils.getSystemOS().equals(WINDOWS)){
                fileRealPath = fileRealPath.replaceAll("\\\\", "/");
            }
            File file = new File(fileRealPath);
            /*设置可读*/
            file.setReadable(true);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            /*表头读取*/
            reader.readLine();
            String dataValue;
            //while循环读取每一行
            //下面是一行的数据分割后，对应数据类型拼装values
            List<String> valuesList = new ArrayList<>();
            int currentLine = 1;
            /*读取文件行*/
            while ((dataValue = reader.readLine()) != null) {
                String[] dataValues = dataValue.split(",", -1);
                if (dataValues == null || dataValues.length < columnCodes.size()) {
                    break;
                }
                StringJoiner values = new StringJoiner(",");
                StringJoiner priStr = new StringJoiner(",");
                /*对已配置字段进行读取*/
                for (int i = 0; i < columnCodes.size(); i++) {
                    /*字段code*/
                    String itemCode = columnCodes.get(i);
                    /*字段类型*/
                    String typeName = columnTypes.get(i);
                    /*字段名称*/
                    String itemName = columnNames.get(i);
                    /*字段在文件中的顺序*/
                    int itemOrder = Integer.parseInt(columnOrders[i]);
                    String str = dataValues[itemOrder];
                    /*判断字段不为空*/
                    if (StringUtils.isEmpty(str) && StringUtils.equals("NO", isNullList.get(i))) {
                        errorText = "第" + currentLine + "行" + itemName + "字段不允许为空";
                        break;
                    } else if (StringUtils.isEmpty(str) && StringUtils.equals("YES", isNullList.get(i))) {
                        str = "null";
                    } else {
                        //字段不为空 判断字段类型
                        if (StringUtils.isNotBlank(typeName)) {
                            if ("date".equals(typeName.toLowerCase())) {
                                str = isDate(str,typeName);
                                if(StringUtils.isNotBlank(str)){
                                    str = String.format("%s%s%s", "str_to_date('", str, "','%Y-%m-%d')");
                                }else{
                                    errorText = "第" + currentLine + "行" + itemName + "字段单元格为自定义格式yyyy-mm-dd ，文字格式为2022-01-01";
                                    break;
                                }

                            } else if ("datetime".equals(typeName.toLowerCase())) {
                                str = isDate(str,typeName);
                                if(StringUtils.isNotBlank(str)){
                                    str = String.format("%s%s%s", "str_to_date('", str, "','%Y-%m-%d %H:%i:%s')");
                                }else{
                                    errorText = "第" + currentLine + "行" + itemName + "字段单元格为自定义格式yyyy-mm-dd hh:mm:ss，文字格式为2022-01-01 00:00:00";
                                    break;
                                }
                            } else {
                                if("decimal".equals(typeName.toLowerCase())){
                                    if(isNumber(str.trim())){
                                        str = String.format("%s%s%s", "'", str.trim(), "'");
                                    }else if(ObjectUtils.isEmpty(str.trim())){
                                        str = "null";
                                        str = String.format("%s",  str);
                                    }else{
                                        errorText = "第" + currentLine + "行" + itemName + "字段为数字类型,读取值【"+str+"】";
                                        break;
                                    }
                                }else{
                                    str = String.format("%s%s%s", "'", str, "'");
                                }
                            }
                        } else {
                            str = String.format("%s%s%s", "'", str, "'");
                        }
                    }
                    /*判断是否为主键*/
                    long num = priKey.stream().filter(string -> itemCode.equals(string)).count();
                    if (num > 0) {
                        if (StringUtils.equals("decimal", typeName)) {
                            Double d1 = new Double(dataValues[itemOrder].toString());
                            BigDecimal b1 = new BigDecimal(d1);
                            priStr.add(b1.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                        } else {
                            priStr.add(dataValues[itemOrder]);
                        }
                    }
                    values.add(str);
                }
                if(StringUtils.isNotBlank(errorText)){
                    break;
                }
                // 存入id
                values.add(String.format("%s%s%s", "'", UUID.randomUUID().toString().replaceAll("-", ""), "'"));
                valuesList.add(values.toString());
                currentLine++;
            }
            if(StringUtils.isNotBlank(errorText)){
                throw new Exception();
            }
            //拼装sql语句的表名，字段，values，ON DUPLICATE KEY UPDATE的条件
            SqlParams sqlParams = new SqlParams();
            sqlParams.setTableName(typeCode);
            columnCodes.add(Variable.ID);
            sqlParams.setColumns(StringUtils.join(columnCodes, ","));
            //ON DUPLICATE KEY UPDATE的条件
            if (updateJoiner.length() > 0) {
                sqlParams.setUpdateParams(String.format("%s%s", " ON DUPLICATE KEY UPDATE ", updateJoiner.toString()));
            } else {
                sqlParams.setUpdateParams("");
            }
            //拼装导入数据
            sqlParams.setValueList(valuesList);
            sqlSession.insert(NAMESPACE + ".insertLoadData", sqlParams);
            //拼装上传记录信息
            record.setState("2");
            /*更新记录信息*/
            updateRecord(record);
            if (file.exists()) {
                reader.close();
                file.delete();
            }
            backResult.put("state", "success");
            backResult.put("message", "加载成功");
            return backResult;
        } catch (Exception e) {
            String s = errorText;
            if(StringUtils.isBlank(s)){
                s = "加载失败！";
            }
            /*返回信息*/
            backResult.put("state", "warning");
            backResult.put("message", s);
            /*更新信息*/
            record.setState("3");
            record.setErrorText(s);
            /*更新记录信息*/
            updateRecord(record);
            logger.error(e.getMessage());
            return backResult;
        }

    }


    /**
     * 更新上传加载记录信息
     **/
    public void updateRecord(LoadRecord record) {
        sqlSession.update(NAMESPACE + ".updateRecord", record);
    }


    /**
     * @description: 删除加载数据并删除文件
     * @author: FFP
     * @time: 2022/1/19 10:17
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteData(Map argsMap) {
        /*获取当前加载记录*/
        LoadRecord record = sqlSession.selectOne(NAMESPACE + ".selectOneRecord", argsMap);
        /*获取文件路径*/
        String filePath = record.getFilePath();
        File file = new File(uploadImagePath + filePath);
        if (file.exists()) {
            file.delete();
        }
        sqlSession.delete(NAMESPACE + ".deleteOneData", argsMap);
    }





    public String getPriStr(List<String> priStr, Map<String, String> data) {
        StringJoiner str = new StringJoiner(",");
        for (String pri : priStr) {
            if (data.containsKey(pri)) {
                if (StringUtils.isBlank(String.valueOf(data.get(pri)))) {
                    str.add("null");
                } else {
                    str.add(String.valueOf(data.get(pri)));
                }
            } else {
                str.add("null");
            }
        }
        return str.toString();
    }

    /**
     * 通过正则表达式判断字符串是否为数字
     * @param str
     * @return
     */
    private static boolean isNumber(String str) {
        return str.matches("-?[0-9]+.?[0-9]*");
    }

    /**
     * 通过正则表达式判断字符串是否为数字
     * @param value
     * @param type
     * @return
     */
    private String isDate(String value, String type){
        String resultValue = "";
        String dateString = "";
        String timeString = "";
        String[] values = value.split(" ");
        if(values.length > 1){
            dateString = values[0];
            timeString = values[1];
        }else{
            dateString = value;
        }
        dateString = getValue(dateString);
        try{
            if(DATE.equals(type.toUpperCase())){
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date = LocalDate.parse(dateString, formatter);
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                resultValue = date.format(formatter);
            }else{
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime date = LocalDateTime.parse(String.format("%s %s", dateString, timeString), formatter);
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                resultValue = date.format(formatter);
            }
        }catch (Exception e){

        }
        return resultValue;
    }

    /**
     * 补全日期信息
     * @return
     */
    private String getValue(String value){
        String resultValue = value.replace("/", "-");
        String[] values = resultValue.split("-");
        if(values.length == 1){
            resultValue = String.format("%s-01-01",values[0]);
        }
        if(values.length == TWO){
            String month = values[1];
            if(month.length() == 1){
                month = String.format("0%s",month);
            }
            resultValue = String.format("%s-%s-01",values[0],month);
        }
        if(values.length == THREE){
            String month = values[1];
            if(month.length() == 1){
                month = String.format("0%s",month);
            }
            String day = values[2];
            if(day.length() == 1){
                day = String.format("0%s",day);
            }
            resultValue = String.format("%s-%s-%s",values[0],month, day);
        }
        return resultValue;
    }


    /**
     * @description: 删除
     * @author: FFP
     * @time: 2022/1/19 10:17
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMaintenanceRow(Map argsMap) {
        String ids = String.valueOf(argsMap.get("ids"));
        String[] list = ids.split(",");
        if (StringUtils.isNotBlank(ids)) {
            argsMap.put("allData", false);
        } else {
            argsMap.put("allData", true);
        }
        argsMap.put("list", list);
        sqlSession.delete(NAMESPACE + ".deleteRow", argsMap);
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> uploadFile(MultipartFile file, String projectId, String typeId, String stepId, String nodeId, String typeCode, String parentType, String userCode) {
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = org.springframework.util.StringUtils.getFilenameExtension(originalFilename);
        if (!acceptUploadFileTypes.contains(filenameExtension.toLowerCase())) {
            throw new RuntimeException(String.format("系统只接受[%s]文件类型", acceptUploadFileTypes.stream().collect(Collectors.joining(","))));
        }
        Map result = new HashMap();
        List<TableConfig> tableHead = selectTableHead(typeCode);
        //插入名称
        List<String> nameList = tableHead.stream().map(TableConfig::getName).collect(Collectors.toList());
        //插入名称String
        String tableColumnName = StringUtils.join(nameList, ",");
        //插入字段代码
        List<String> codeList = tableHead.stream().map(TableConfig::getCode).collect(Collectors.toList());
        //配置后文件序号
        List<Integer> indexList = new ArrayList<>();
        //配置后文件列code
        List<String> resultCodeList = new ArrayList<>();
        //数据加载历史
        LoadRecord record = new LoadRecord();
        try {
            //匹配字段
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "GBK"));
            String csvtitle = reader.readLine();
            record.setFileTitle(csvtitle);
            if (StringUtils.equals(tableColumnName, csvtitle)) {
                record.setState("1");
            } else {
                record.setState("0");
            }
            List<String> collectTitle = Arrays.stream(csvtitle.split("\\,")).collect(Collectors.toList());
            for (String item : collectTitle) {
                if (nameList.contains(item)) {
                    int i = nameList.indexOf(item);
                    indexList.add(i);
                    resultCodeList.add(codeList.get(i));
                }
            }
            record.setAfterOrder(StringUtils.join(indexList, ","));
            record.setAfterCode(StringUtils.join(resultCodeList, ","));

            String id = UUIDUtils.generateUuid();
            String filePath = String.format("%s/%s/%s", projectId, "dataFile", parentType);
            String fileName = id + ".csv";
            org.springframework.core.io.Resource targetResource = resourceLoader.getResource(String.format("%s%s/%s", uploadImagePath, filePath,fileName));
            //服务器生成文件
            FileUtil.createFile(file.getInputStream(), (WritableResource) targetResource);
            //组装参数
            record.setId(id);
            record.setType(typeId);
            record.setParentType(parentType);
            record.setFileName(file.getOriginalFilename());
            record.setFileSize(file.getSize());
            record.setFileSource("本地文件");
            record.setFilePath(String.format("%s/%s", filePath, fileName));
            record.setOperator(SecurityUtils.getUsername());
            record.setNodeId(nodeId);
            record.setStepId(stepId);
            record.setProjectId(projectId);
            sqlSession.update(NAMESPACE + ".insertLoadRecord", record);
            result.put("msg","上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            record.setErrorText("文件上传错误");
            result.put("msg","上传失败");
        }
        System.out.println(result);
        return result;
    }

    /**
     * @description: 数据维护 新增
     * @author Ligw
     * @date 2022/7/15 16:59
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveRow(SaveRow params) {
        try {
            SqlParams sql = new SqlParams();
            sql.setTableName(params.getTableName());
            List<String> columnList = new ArrayList<>();
            StringJoiner valueList = new StringJoiner(",");
            StringJoiner updateList = new StringJoiner(",");
            List<TableConfig> headList = sqlSession.selectList(NAMESPACE + ".selectTableHead", params.getTableName());
            Map<String,String> data = params.getData();
            for(TableConfig config:headList){
                columnList.add(config.getCode());
                if(!"PRI".equals(config.getPrimaryKey())){
                    updateList.add(config.getCode()+"= values("+config.getCode()+")");
                }
                String str = "null";
                if(data.containsKey(config.getCode())){
                    str = data.get(config.getCode());
                    if(StringUtils.isBlank(str)){
                        str = "null";
                    }else if ("date".equals(config.getType().toLowerCase())) {
                        str = String.format("%s%s%s", "str_to_date('", str, "','%Y-%m-%d')");
                    } else if ("datetime".equals(config.getType().toLowerCase())) {
                        str = String.format("%s%s%s", "str_to_date('", str, "','%Y-%m-%d %H:%i:%s')");
                    } else {
                        str = String.format("%s%s%s", "'", str, "'");
                    }
                }
                valueList.add(str);
                // 存入id
            }
            // id
            if(StringUtils.isEmpty(params.getId())){
                columnList.add(Variable.ID);
                valueList.add(String.format("%s%s%s", "'", UUID.randomUUID().toString().replaceAll("-", ""), "'"));
            } else {
                columnList.add(Variable.ID);
                valueList.add(String.format("%s%s%s", "'", params.getId(), "'"));
            }

            sql.setColumns(StringUtils.join(columnList, ","));
            List<String> value = new ArrayList<>();
            value.add(valueList.toString());
            sql.setValueList(value);
            if (updateList.length() > 0) {
                sql.setUpdateParams(String.format("%s%s", " ON DUPLICATE KEY UPDATE ", updateList.toString()));
            } else {
                sql.setUpdateParams("");
            }
            sqlSession.insert(NAMESPACE + ".insertLoadData", sql);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.ok().build();
        }
    }

    public List<String> getExportData(String tableName, String projectId) {
        List<String> list = new ArrayList<>();
        String codes = "";
        Map<String, Object> params = new HashMap();
        params.put("projectId", projectId);
        params.put("tableName", tableName);
        Map<String, Object> head = sqlSession.selectOne(NAMESPACE + ".selectTableHeadString", tableName);
        if (head.get(CODE) != null) {
            String code = head.get("code").toString();
            List<String> collect = Arrays.asList(code.split(",")).stream().map(item -> {
                return "IFNULL(" + item + ", '')";
            }).collect(Collectors.toList());
            codes = StringUtils.join(collect, ",");
        }
        StringJoiner updateJoiner = new StringJoiner(",");
        updateJoiner.add("','");
        updateJoiner.add(codes);
        params.put("head", updateJoiner.toString());
        list.add(head.get("name").toString());
        List<String> result = sqlSession.selectList(NAMESPACE + ".selectExportData", params);
        list.addAll(result);
        return list;
    }

    /**
     * 更新文件配置信息
     **/
    public void updateRecordInfo(FileSetResult fileSetResult) {
        if (!fileSetResult.getFileSetInfo().isEmpty() && fileSetResult.getFileSetInfo() != null && fileSetResult.getRecord() != null) {
            List<String> tableCode = new ArrayList<>();
            List<String> indexList = new ArrayList<>();
            List<FileSetInfo> fileSetInfo = fileSetResult.getFileSetInfo();
            LoadRecord record = fileSetResult.getRecord();
            for (int i = 0; i <= fileSetInfo.size() - 1; i++) {
                if (StringUtils.isNotBlank(fileSetInfo.get(i).getTableCode())) {
                    indexList.add(String.valueOf(i));
                    tableCode.add(fileSetInfo.get(i).getTableCode());
                }
            }
            record.setAfterCode(StringUtils.join(tableCode, ","));
            record.setAfterOrder(StringUtils.join(indexList, ","));
            record.setState("1");
            sqlSession.update(NAMESPACE + ".updateRecord", record);
        }
    }

}
